package orion.cricScoreCard.Activity;

import orion.cricScoreCard.Entities.BattingPlayer;
import orion.cricScoreCard.Entities.CurrentPlayers;
import orion.cricScoreCard.Entities.Match;
import orion.cricScoreCard.Utilities.ScoringFunctions;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ScoreCard extends Activity {

	private TextView _txtBattingTeam;
	private TextView _txtOver;
	private TextView _txtScore;
	private TextView _txtStriker;
	private TextView _txtNonStriker;
	private TextView _txtBowler;
	private TextView _txtThisOver;

	private ImageView imgBall1;
	private ImageView imgBall2;
	private ImageView imgBall3;
	private ImageView imgBall4;
	private ImageView imgBall5;
	private ImageView imgBall6;

	private int counter = 0; // for counting the balls in each over
	private int over = 0;

	public int runs;
	public int balls;
	public int wikets = 0;

	private BattingPlayer _battingPlayerOne;
	private BattingPlayer _battingPlayerTwo;
	private BattingPlayer _battingPlayerOut;

	private static String outType;
	private static String outBy;

	private static Match _match = new Match();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.score);
		init();
		initContents();
	}

	// Setting Controls and Player Variables(Batting Class)
	private void initContents() {
		_txtBattingTeam.setText(_match.getBattingTeam());
		_battingPlayerOne.set_teamName(_match.getBattingTeam());
		_battingPlayerTwo.set_teamName(_match.getBattingTeam());
		_battingPlayerOne.set_playerName(CurrentPlayers.getStriker()
				.get_playerName());
		_battingPlayerTwo.set_playerName(CurrentPlayers.getNon_striker()
				.get_playerName());
		_txtBowler.setText(CurrentPlayers.getBowler().get_playerName());
		_txtNonStriker
				.setText(CurrentPlayers.getNon_striker().get_playerName());
		_txtStriker.setText(CurrentPlayers.getStriker().get_playerName());
	}

	// Change Strikers
	private void changeStickerText() {
		_txtNonStriker.setText(CurrentPlayers.getNon_striker().get_playerName()
				+ ": " + CurrentPlayers.getNon_striker().get_run());
		_txtStriker.setText(CurrentPlayers.getStriker().get_playerName()
				+ "*: " + CurrentPlayers.getStriker().get_run());
	}

	// Init Controls & Objects
	private void init() {
		_txtBattingTeam = (TextView) findViewById(R.id.txtBatting);
		_txtOver = (TextView) findViewById(R.id.txtOvers);
		_txtScore = (TextView) findViewById(R.id.txtTeamScore);
		_txtNonStriker = (TextView) findViewById(R.id.txtNonStrikerBat);
		_txtStriker = (TextView) findViewById(R.id.txtStrikerBat);
		_txtBowler = (TextView) findViewById(R.id.txtBowling);
		_txtThisOver = (TextView) findViewById(R.id.txtThisOver1);

		imgBall1 = (ImageView) findViewById(R.id.imageBall1);
		imgBall2 = (ImageView) findViewById(R.id.imageBall2);
		imgBall3 = (ImageView) findViewById(R.id.imageBall3);
		imgBall4 = (ImageView) findViewById(R.id.imageBall4);
		imgBall5 = (ImageView) findViewById(R.id.imageBall5);
		imgBall6 = (ImageView) findViewById(R.id.imageBall6);

		_battingPlayerOne = CurrentPlayers.getStriker();
		_battingPlayerTwo = CurrentPlayers.getNon_striker();
		_battingPlayerOut = CurrentPlayers.getPlayerOut();
	}

	// Button Methods
	public void btnZero_Click(View v) {
		thisOver(0);
		counter++;
		setChange();
		changeStickerText();
	}

	public void btnOne_Click(View v) {
		thisOver(1);
		counter++;
		setChange();
		ScoringFunctions.swap();
		changeStickerText();
	}

	public void btnTwo_Click(View v) {
		thisOver(2);
		counter++;
		setChange();
		changeStickerText();
	}

	public void btnThree_Click(View v) {
		thisOver(3);
		counter++;
		setChange();
		ScoringFunctions.swap();
		changeStickerText();
	}

	public void btnFour_Click(View v) {
		thisOver(4);
		counter++;
		setChange();
		changeStickerText();
	}

	public void btnSix_Click(View v) {
		thisOver(6);
		counter++;
		setChange();
		changeStickerText();

	}
	
	public void btnSwap_Click(View v) {
		ScoringFunctions.swap();
		changeStickerText();
	}

	public void btnByes_Click(View v) {
		showExtraOption("B");
	}

	public void btnNoBall_Click(View v) {
		showExtraOption("Nb");
	}

	public void btnWide_Click(View v) {
		showExtraOption("wd");
	}

	public void btnOut_Click(View v) {
		showOutOption();
		wikets++;
		_txtThisOver.setText(_txtThisOver.getText().toString() + "W" + "  ");
		counter++;
		setChange();
	}

	/*
	 * public void btnSameBall_Click(View v) { setScore(); }
	 */

	private void thisOver(int i) {
		runs = runs + i;
		_txtThisOver.setText(_txtThisOver.getText().toString() + i + "  ");
		setRun(CurrentPlayers.getStriker(), i);
	}

	// Extras calculations
	private void thisOverExtra(String extraType, int extraRun) {
		runs = runs + extraRun;
		if (extraType == "B") {
			counter++;
			setOvers();
			setImageBalls();
		} else if (extraType == "wd") {
			runs = runs + 1;
		} else if (extraType == "Nb") {
			runs = runs + 1;
			CurrentPlayers.getStriker().set_run(extraRun);
			if (extraRun == 4) {
				CurrentPlayers.getStriker().set_four();
			} else if (extraRun == 6) {
				CurrentPlayers.getStriker().set_six();
			}
		}
		if (extraRun == 1 || extraRun == 3) {
			ScoringFunctions.swap();
			changeStickerText();
		}
		_txtThisOver.setText(_txtThisOver.getText().toString() + extraRun
				+ extraType + "  ");
		setChange();
	}

	// Setting runs, number of balls faced for
	private void setRun(BattingPlayer _batting, int run) {
		_batting.set_run(run);
		_batting.set_ball();
		if (run == 4) {
			_batting.set_four();
		} else if (run == 6) {
			_batting.set_six();
		}
	}

	// Getting and Setting Match Details
	public static void setMatch(Match match) {
		_match = match;
	}

	// Changing Score Board
	private void setChange() {
		setScore();
		setImageBalls();
		setOvers();
	}

	// Changing Score in score board
	private void setScore() {
		_txtScore.setText(runs + "/" + wikets);
	}

	// Setting Ball Images in score board
	private void setImageBalls() {
		if (counter == 1) {
			imgBall1.setVisibility(1);
		} else if (counter == 2) {
			imgBall2.setVisibility(1);
		} else if (counter == 3) {
			imgBall3.setVisibility(1);
		} else if (counter == 4) {
			imgBall4.setVisibility(1);
		} else if (counter == 5) {
			imgBall5.setVisibility(1);
		} else if (counter == 6) {
			imgBall6.setVisibility(1);
			Toast.makeText(getApplicationContext(), "Over Completed",
					Toast.LENGTH_LONG).show();
			_txtThisOver.setText("");
			counter = 0;
			imgBall1.setVisibility(View.INVISIBLE);
			imgBall2.setVisibility(View.INVISIBLE);
			imgBall3.setVisibility(View.INVISIBLE);
			imgBall4.setVisibility(View.INVISIBLE);
			imgBall5.setVisibility(View.INVISIBLE);
			imgBall6.setVisibility(View.INVISIBLE);

		} else {

		}

	}

	// Setting Overs in score board
	private void setOvers() {
		boolean flag = true;
		if (counter == 0) {
			over++;
			flag = false;
		}
		if (!flag) {
			_txtOver.setText(over + ".0");
			showTextNewBowler();
		} else {
			_txtOver.setText(over + "." + counter);
		}
		GameOver();
	}

	public void GameOver() {
		if ((over == ScoringFunctions.overs) || (wikets >= 10)) {
			counter = 0; // for counting the balls in each over
			over = 0;
			showOptions();
			// match over setting
		}
	}

	private void showOutOption() {

		final CharSequence[] list = { "Stumped", "Catch", "Runout", "Bowled",
				"LBW", "Hit Wicket" };
		new AlertDialog.Builder(this).setIcon(R.drawable.ic_launcher)
				.setTitle("CricScore")
				.setItems(list, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						String str = (String) list[which];
						outType = str;
						if (str.equals("Catch") || str.equals("Runout")
								|| str.equals("Stumped")) {
							if (str.equals("Runout")) {
								showRunOutOptions();
							} else {
								CurrentPlayers.setOutPlayer(CurrentPlayers
										.getStriker());
								showTextAlert(outType);
							}

						} else {
							outBy = CurrentPlayers.getBowler().get_playerName();
							_battingPlayerOut.set_out(outType + ", " + outBy);
							ScoringFunctions.playerOut(getApplicationContext(),
									_battingPlayerOut, outBy, outType);
							showTextNewBatsman();
						}
					}
				}).show();

	}

	private void showExtraOption(final String extraType) {

		final CharSequence[] list = { "0", "1", "2", "3", "4", "6" };
		new AlertDialog.Builder(this).setIcon(R.drawable.ic_launcher)
				.setTitle("Extra Run taken")
				.setItems(list, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						String str = (String) list[which];
						if (str.equals("0")) {
							thisOverExtra(extraType, 0);

						} else if (str.equals("1")) {
							thisOverExtra(extraType, 1);

						} else if (str.equals("2")) {
							thisOverExtra(extraType, 2);

						} else if (str.equals("3")) {
							thisOverExtra(extraType, 3);

						} else if (str.equals("4")) {
							thisOverExtra(extraType, 4);

						} else if (str.equals("6")) {
							thisOverExtra(extraType, 6);
						}
					}
				}).show();

	}

	private void showTextAlert(final String str) {

		final AlertDialog.Builder alert = new AlertDialog.Builder(this);
		final EditText input = new EditText(this);
		alert.setView(input).setIcon(R.drawable.ic_launcher)
				.setTitle("CricScore").setMessage(str + " By:")
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						outBy = input.getText().toString();
						outType = str;
						_battingPlayerOut.set_out(outType + ", " + outBy);
						ScoringFunctions.playerOut(getApplicationContext(),
								_battingPlayerOut, outBy, outType);
						showTextNewBatsman();
					}
				}).show();
	}

	private void showTextNewBatsman() {

		final AlertDialog.Builder alert = new AlertDialog.Builder(this);
		final EditText batsman = new EditText(this);
		alert.setView(batsman).setIcon(R.drawable.ic_launcher)
				.setTitle("CricScore").setMessage("New Man In")
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						Log.i("LOG:", batsman.getText().toString());
						String bat = batsman.getText().toString();
						_txtStriker.setText(bat);

					}
				}).show();
	}

	private void showTextNewBowler() {

		final AlertDialog.Builder alert = new AlertDialog.Builder(this);
		final EditText bowler = new EditText(this);
		alert.setView(bowler).setIcon(R.drawable.ic_launcher)
				.setTitle("CricScore").setMessage("New Bowler In")
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						Log.i("LOG:", bowler.getText().toString());
						String bowl = bowler.getText().toString();
						_txtBowler.setText(bowl);
					}
				}).show();
	}

	private void showOptions() {
		new AlertDialog.Builder(this)
				.setIcon(R.drawable.ic_launcher)
				.setTitle("CricScore")
				.setMessage("Game Over!!!")
				.setPositiveButton("Continue",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								Intent playerInt = new Intent(
										getApplicationContext(),
										TeamDetails.class);
								Bundle data = new Bundle();
								data.putString("Batting",
										_match.getBowlingTeam());
								data.putString("Bowling",
										_match.getBattingTeam());
								data.putString("Overs", _match.getOvers() + "");
								playerInt.putExtras(data);
								startActivity(playerInt);
							}
						}).show();

	}

	private void showRunOutOptions() {
		new AlertDialog.Builder(this)
				.setIcon(R.drawable.ic_launcher)
				.setTitle("CricScore")
				.setMessage("Out!!!")
				.setPositiveButton(
						CurrentPlayers.getStriker().get_playerName(),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								_battingPlayerOut = CurrentPlayers.getStriker();
								showTextAlert("Runout");
							}
						})
				.setNegativeButton(
						CurrentPlayers.getNon_striker().get_playerName(),
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								_battingPlayerOut = CurrentPlayers
										.getNon_striker();
								showTextAlert("Runout");
							}
						}).show();

	}
}
